import {Component, OnInit, Input} from '@angular/core';
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import smooth from 'chaikin-smooth';
import Draw from 'ol/interaction/Draw.js';
import {UtilComponent} from '../../interface/util-component.interface';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';

@Component({
    selector: 'kylin-smooth-line',
    templateUrl: './smooth-line.component.html',
    styleUrls: ['./smooth-line.component.less']
})
export class SmoothLineComponent implements OnInit, UtilComponent {

    hasContent = true;
    map: Map;

    @Input() set data(val) {
        Object.assign(this, val);
    };

    numIterations = 5;
    shallSmoothen = true;
    vectorLayer: any;
    drawSource: any;
    draw: Draw;

    constructor() {
    }

    ngOnInit() {
        this.drawSource = new VectorSource({});
        this.vectorLayer = new VectorLayer({
            source: this.drawSource
        });
        this.map.addLayer(this.vectorLayer);
        this.turnOn();
    }

    turnOn() {
        this.draw = new Draw({
            source: this.drawSource,
            type: 'LineString' as any
        });
        this.map.addInteraction(this.draw);
        this.draw.on('drawend', (event) => {
            if (!this.shallSmoothen) {
                return;
            }
            const feat = event.feature;
            const geometry = feat.getGeometry();
            const coords = (geometry as any).getCoordinates();
            const smoothened = this.makeSmooth(coords, parseInt(this.numIterations + '', 10) || 5);
            (geometry as any).setCoordinates(smoothened);
        });
    }

    turnOff() {
        this.map.removeLayer(this.vectorLayer);
        this.map.removeInteraction(this.draw);
    }

    cancel(options?: any): any {
        this.turnOff();
    }

    makeSmooth(path, numIterations) {
        numIterations = Math.min(Math.max(numIterations, 1), 10);
        while (numIterations > 0) {
            path = smooth(path);
            numIterations--;
        }
        return path;
    }
}
